

//参数类型
import {_} from "../../util/UtilTs";
import {Ctx} from "../../index";

//参数类型
export abstract class ParaTypes{
    [x:string]:any;
    name:string; //类型名
    require:boolean = true; //必填参数
    default:any;//默认值
    errMsg:string;//自定义错误信息
    b:(self:ParaTypes,ctx:Ctx)=>void;


    constructor(opts,name){
        this.name = name;
        _.merge(this,opts);
    }

    abstract validator:(self,ctx:Ctx,key:string,param:any)=>any; //验证器

    //成功了返回 要转换的结果，不成功返回false
    doValidate(ctx:Ctx, key:string,val):any{
        this.b && this.b(this,ctx);
        return this.validator(this,ctx,key,val);
    }

    returnDefaultOrFalse(){
        const hasDef = _.has(this,"default");
        const ret = this.default || undefined;
        if(hasDef || !this.require){
            return ret;
        }
        else {
            return false
        }
    }


    static create(name,opts:Partial<ParaTypes>,validator){

        const clazz= class extends ParaTypes {
            validator = validator.bind(this);
        };

        const options = opts || {};
        const ret = new clazz(options,name);
        return ret;
    }

}





export const PType = {

    int:(opts?:Partial<ParaTypes>)=> ParaTypes.create('int',opts,(self,ctx:Ctx,key,param)=>{
        const ret = _.toNumber(param);
        if(_.isInteger(ret)){
            return ret;
        }else {
            if(param != undefined){
                return false;
            }
            else {
                return self.returnDefaultOrFalse();
            }
        }
    }),

    userName:(opts?:Partial<ParaTypes>)=> ParaTypes.create('userName',opts,(self,ctx:Ctx,key,param)=>{
        const reg =/^[a-zA-Z0-9_-]{4,16}$/;
        if (param && reg.test(param) ) {
            return param;
        }else {
            return self.returnDefaultOrFalse();
        }
    }),

};


